package com.jic.member.controller.manage;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.jic.common.base.vo.RestResult;
import com.jic.member.api.rest.MemberRegisterApi;
import com.jic.member.request.UserAddrRequest;
import com.jic.member.request.UserProductRequest;
import com.jic.member.request.UserRegistRequest;
import com.jic.member.request.UserUpdateImage;
import com.jic.member.request.power.UserConstantsProperties;
import com.jic.member.response.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("memberRegister")
public class MemberRegisterController implements MemberRegisterApi {

    @Resource
    private StringRedisTemplate iCache;

    private final static String TOKEN_KEY = "stoken";

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserConstantsProperties userConstantsProperties;
    /**
     * @description: 以用户的code来获取它的token
     * @return:
     * @author: fengrui
     * @time: 2020/12/09 16:08
     */
    @Override
    public String getsAccessToken() {
        String stoken = iCache.opsForValue().get(TOKEN_KEY);
        if (StringUtil.isNotEmpty(stoken)) {
            log.info(stoken);
        }


        String url = userConstantsProperties.getUocUrlWx()+"/oauth/token";
        //构造请求UOC接口
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        postMethod.addParameter("grant_type", "client_credentials");
        postMethod.addParameter("client_id", userConstantsProperties.getSclientId());
        postMethod.addParameter("client_secret",  userConstantsProperties.getSclientSecret());
        //postMethod.addParameter("client_id", userConstantsProperties.getClientId());
        //postMethod.addParameter("client_secret", userConstantsProperties.getClientSecret());
        String response = null;
        log.info("发起请求:{}", url);
        //postMethod.addRequestHeader("Authorization", "Bearer[] " + authorization);
        try {
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            postMethod.releaseConnection();
        }
        log.info(response);
        JSONObject obj = JSONObject.parseObject(response);
        String accessToken = obj.getString("access_token");
        //String refreshToken = obj.getString("refresh_token");
        Assert.isTrue(StringUtil.isNotEmpty(accessToken), "登陆失败！");
        //将应用级session缓存到redis中，有效期10天
        iCache.opsForValue().set(TOKEN_KEY, accessToken, 10, TimeUnit.DAYS);
        System.out.println(accessToken);

        return accessToken;
    }

    /**
     * @description: 获取用户的图片
     * @return:
     * @author: fengrui
     * @time: 2020/12/09 16:17
     */
    @Override
    public RestResult<ImageResponse> getMemberImage() {
        String url = userConstantsProperties.getUocUrlWx() + "/v1/captcha";
        //构造请求UOC接口
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        String response = null;
        log.info("发起请求:{}", url);
        // postMethod.addRequestHeader("Authorization", "Bearer " + iCache.get("stoken"));
        String token = getsAccessToken();
        postMethod.addRequestHeader("Authorization", "Bearer " + token);
        try {
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            postMethod.releaseConnection();
        }
        log.info(response);
        JSONObject obj = JSONObject.parseObject(response);
        ImageResponse imageResponse = new ImageResponse();
        imageResponse.setImage(obj.getString("captcha_token"));
        imageResponse.setToken(obj.getString("captcha_image"));


        return RestResult.success(imageResponse);
    }

    @Override
    public RestResult<?> skipMyproduct(UserProductRequest user) {
        String url = userConstantsProperties.getUocUrlWx() + "/v2/haier/client/jump";
        //构造请求UOC接口
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        String response = null;
        user.setTarget(userConstantsProperties.getTarget());
        user.setRedirect_uri_product(userConstantsProperties.getRedirect_uri_product());

        log.info("清洗卡入参："+user.toString());
        postMethod.addRequestHeader("Content-Type", "application/json");
        postMethod.addRequestHeader("Authorization", "Bearer " + user.getToken());


        try {
            RequestEntity se = new StringRequestEntity(JSONObject.toJSON(user).toString(), "application/json", "UTF-8");
            postMethod.setRequestEntity(se);
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        }catch (IOException e) {
            log.error("执行http请求跳转海知友失败," + e.getMessage());
            e.printStackTrace();
        }
        return RestResult.success(response);
    }

    @Override
    public RestResult<?> skipCheckIn(UserProductRequest user) {
        String url = userConstantsProperties.getUocUrlWx() + "/v2/haier/client/jump";
        //构造请求UOC接口
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        String response = null;
        user.setTarget(userConstantsProperties.getTarget());
        user.setRedirect_uri_product(userConstantsProperties.getRedirect_uri_checkIn());
        log.info("签到入参："+user.toString());
        postMethod.addRequestHeader("Content-Type", "application/json");
        postMethod.addRequestHeader("Authorization", "Bearer " + user.getToken());


        try {
            RequestEntity se = new StringRequestEntity(JSONObject.toJSON(user).toString(), "application/json", "UTF-8");
            postMethod.setRequestEntity(se);
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        }catch (IOException e) {
            log.error("执行http请求跳转海知友失败," + e.getMessage());
            e.printStackTrace();
        }
        return RestResult.success(user);
    }

    /**
     * @param update
     * @description: 修改用户头像
     * @return:
     * @author: fengrui
     * @time: 2020/12/09 21:55
     */
    @Override
    public RestResult<?> uploadImage(UserUpdateImage update) throws FileNotFoundException {
        String url = userConstantsProperties.getUocUrlWx() + "/v2/user/avatar/upload";
        //构造请求UOC接口
        HttpClient httpClient = new HttpClient();
        PutMethod putMethod = new PutMethod(url);
        String response = null;
        putMethod.addRequestHeader("Authorization", "Bearer " + update.getToken());
        FilePart fp = new FilePart("file", update.getFile());
        Part[] parts = {fp};
        MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts,putMethod.getParams());
        putMethod.setRequestEntity(requestEntity);
        try {
            httpClient.executeMethod(putMethod);
            response = putMethod.getResponseBodyAsString();
        }catch (IOException e) {
            log.error("上传头像失败," + e.getMessage());
            e.printStackTrace();
        }
        return RestResult.success(response);
    }

    @Override
    public RestResult<?> sendSms2(JSONObject param) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phone_number", param.get("phone"));
        jsonObject.put("scenario", param.get("type"));
        if (StringUtil.isNotEmpty(param.get("captcha_token").toString())) {
            jsonObject.put("captcha_token", param.get("captcha_token"));
        }
        if (StringUtil.isNotEmpty(param.get("captcha_answer").toString())) {
            jsonObject.put("captcha_answer", param.get("captcha_answer"));
        }

        String url = userConstantsProperties.getUocUrlWx() + "/v2/sms-verification-code/send";
        //构造请求UOC接口
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("Content-Type", "application/json");
        String response = null;
        log.info("发起请求:{}", url);
        try {
            RequestEntity jsonEntity = new StringRequestEntity(jsonObject.toString(), "application/json", "UTF-8");
            postMethod.setRequestEntity(jsonEntity);
            String token = getsAccessToken();
            postMethod.addRequestHeader("Authorization", "Bearer " + token);
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            postMethod.releaseConnection();
        }
        log.info(response);
        JSONObject obj = JSONObject.parseObject(response);
        Boolean success = obj.getBoolean("success");
        String delay = obj.getString("delay");

        return RestResult.success(delay);
    }

    @Override
    public RestResult<?> sendSms(JSONObject param) {
//        String url = userConstantsProperties.getUocUrlWx() + "/v2/sms-verification-code/send";
//
//        JSONObject jsonObject = new JSONObject();
//
//
//        if (StrKit.isEmpty(StrKit.toSafeString(param.get("captcha_token"))) || StrKit.isEmpty(StrKit.toSafeString(param.get("captcha_answer")))) {
//            return Result.fail("图片验证码不能为空");
//        }
//
//
//        jsonObject.put("phone_number", StrKit.toSafeString(param.get("phone")));
//        jsonObject.put("scenario", StrKit.toSafeString(param.get("type")));
//        jsonObject.put("captcha_token", StrKit.toSafeString(param.get("captcha_token")));
//        jsonObject.put("captcha_answer", StrKit.toSafeString(param.get("captcha_answer")));
//
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//        String token = getsAccessToken();
//        headers.add("Authorization", "Bearer " + token);
//        HttpEntity<String> requestEntity = new HttpEntity<>(jsonObject.toString(), headers);
//        //执行HTTP请求，将返回的结构使用ResultVO类格式化
//        ResponseEntity<String> response;
//        try{
//            response = restTemplate.postForEntity(url, requestEntity, String.class);
//        }catch (Exception ex){
//            log.error("发送验证码异常，url：" +url+",入参：" + jsonObject,ex);
////            return Result.fail("短信未成功发送，请重新发送");
//        }


//        ResultDto resultDto = JsonUtil.parseObject(response.getBody(), ResultDto.class);
//
//
//        Result result;
//        if (resultDto.isSuccess() || StringUtil.isEmpty(resultDto.getError())) {
//            result = Result.success();
//            result.addData("delay", resultDto.getDelay());
//        } else {
//            result = Result.fail(UOCDicConfig.getErrorMsg(resultDto.getError()));
//            result.setData(resultDto);
//        }
        return RestResult.success(null);
    }

    @Override
    public RestResult<?> phoneLogin(JSONObject jsonObject) {
//        String url = userConstantsProperties.getUocUrlWx() + "/oauth/token";
//
//
//        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
//        multiValueMap.add("grant_type", "password");
//        multiValueMap.add("connection", "sms");
//        multiValueMap.add("username", StrKit.toSafeString(jsonObject.get("phone")));
//        multiValueMap.add("password", StrKit.toSafeString(jsonObject.get("randCode")));
//        multiValueMap.add("client_id", userConstantsProperties.getSclientId());
//        multiValueMap.add("client_secret", userConstantsProperties.getSclientSecret());
//
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(multiValueMap, headers);
//        //执行HTTP请求，将返回的结构使用ResultVO类格式化
//        ResponseEntity<ResultDto> response = restTemplate.postForEntity(url, requestEntity, ResultDto.class);
//        return RestResult.success(response.getBody());
        return null;
    }

    @Override
    public RestResult<?> getUserInfo(String accessTokenPri) {
//        String url = userConstantsProperties.getUocUrlWx() + "/userinfo";
//
//
//        HttpHeaders headers = new HttpHeaders();
//        HttpMethod method = HttpMethod.GET;
//        headers.add("Authorization", "Bearer " + accessTokenPri);
//        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(null, headers);
//        //执行HTTP请求，将返回的结构使用ResultVO类格式化
//        ResponseEntity<String> response = restTemplate.exchange(url, method, requestEntity, String.class);
//        JSONObject userJson = JSONObject.parseObject(response.getBody());
//        Appuser oAppUser = new Appuser();
//        oAppUser.setUsername(StrKit.toSafeString(userJson.getString("name")));
//        oAppUser.setIdsUserId(StrKit.toSafeInteger(userJson.getString("user_id")));
//        oAppUser.setLoginName(StrKit.toSafeString(userJson.getString("username")));
//        oAppUser.setHeadurl(StrKit.toSafeString(userJson.getString("avatar_url")));
//        oAppUser.setCellphoene(StrKit.toSafeString(userJson.getString("phone_number")));
//        oAppUser.setEmail(StrKit.toSafeString(userJson.getString("email")));
//        oAppUser.setBirthday(StrKit.toSafeString(userJson.getString("birthday")));
//        int sex;
//        if (StrKit.isEmpty(userJson.getString("gender"))){
//            sex = 0;
//        } else if ("male".equals(userJson.getString("gender"))){
//            sex = 1;
//        } else if ("female".equals(userJson.getString("gender"))){
//            sex = 2;
//        } else {
//            sex = 0;
//        }
//        oAppUser.setSex(sex);
//        //设置当前用户的站点ID,目前小程序只有海贝商城
//        oAppUser.setSiteId(EshopConstants.haibeiSiteId);
//
//
//        return oAppUser;
        return null;
    }

    @Override
    public RestResult<?> login(JSONObject param) {
//        String url = userConstantsProperties.getUocUrlWx() + "/oauth/token";
//
//
//        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//        params.add("client_id", userConstantsProperties.getSclientId());
//        params.add("client_secret", userConstantsProperties.getSclientSecret());
//        params.add("grant_type", "password");
//        params.add("connection", "basic_password");
//        params.add("username", StrKit.toSafeString(param.getString("userName")));
//        params.add("password", StrKit.toSafeString(param.getString("pwd")));
//        if (StrKit.isNotEmpty(param.get("captcha_token"))) {
//            params.add("captcha_token", StrKit.toSafeString(param.get("captcha_token")));
//        }
//        if (StrKit.isNotEmpty(param.get("captcha_answer"))) {
//            params.add("captcha_answer", StrKit.toSafeString(param.get("captcha_answer")));
//        }
//
//
//        HttpHeaders headers = new HttpHeaders();
//        HttpMethod method = HttpMethod.POST;
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
//        //执行HTTP请求，将返回的结构使用ResultVO类格式化
//        ResponseEntity<String> response = restTemplate.exchange(url, method, requestEntity, String.class);

//        return JsonUtil.parseObject(response.getBody(), ResultDto.class);
        return null;
    }

    @Override
    public RestResult<?> regist(UserRegistRequest registRequest) throws IOException {
        String url = userConstantsProperties.getUocUrlWx() + "/v1/signup";


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phone_number", registRequest.getPhone());
        jsonObject.put("password", registRequest.getPassword());
        jsonObject.put("verification_code", registRequest.getRandCode());


        //构造请求UOC接口
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);


        RequestEntity jsonEntity = new StringRequestEntity(jsonObject.toString(), "application/json", "UTF-8");
        postMethod.setRequestEntity(jsonEntity);
        String token = getsAccessToken();
        postMethod.addRequestHeader("Content-Type", " application/json");
        postMethod.addRequestHeader("Authorization", "Bearer " + token);
        httpClient.executeMethod(postMethod);
        String response = null;
        log.info("发起请求:{}", url);
        try {
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            postMethod.releaseConnection();
        }
        log.info(response);
        JSONObject obj = JSONObject.parseObject(response);
        Boolean success = obj.getBoolean("success");


        return RestResult.success(success);
    }



    @Override
    public String getTokent(String code) {
        return null;
    }

}
